# -*- coding: utf-8 -*-
'''
Created on 2012-9-4

@author: Leon
'''
# all the imports
import os, random, biz
from flask import Flask, request, current_app, render_template, \
    g, abort, redirect, url_for, send_from_directory
from flask.ext.login import (LoginManager, current_user, login_required,
                             login_user, logout_user, UserMixin, AnonymousUser,
                             confirm_login, fresh_login_required)
from common import connect_db, query_db1
from models import Firm, Product, Tag
from login import ADMIN_USERS, ADMIN_USERS_DICT, Anonymous

from datetime import datetime

# configuration----------------------------------------------------
DATABASE = ''
DEBUG = True
SECRET_KEY = 'SECRET_KEY'
USERNAME = ''
PASSWORD = ''
NEWS_RSS_URL = 'http://cn.bing.com/news/search?q=%E4%BA%91%E8%AE%A1%E7%AE%97' \
               '&qs=n&form=QBNT&pq=%E4%BA%91%E8%AE%A1%E7%AE%97&sc=8-3&sp=-1&sk=&format=rss'

HERE = os.path.dirname(os.path.abspath(__file__))
DATA_FOLDER = os.path.join(HERE, 'data')
DATA_PATH = os.path.join(DATA_FOLDER, 'grape.db')



# create our little application :)------------------------------------
application = app = Flask(__name__)
app.config.from_object(__name__)


# robot.txt--------------------------------------------------------
@app.route('/robots.txt')
def static_from_root():
    return send_from_directory(app.static_folder, request.path[1:])


#login------------------------------------------------


login_manager = LoginManager()
login_manager.init_app(app)

login_manager.anonymous_user = Anonymous
login_manager.login_view = "admin_login"
login_manager.login_message = u"Please log in to access this page."
login_manager.refresh_view = "reauth"


@login_manager.user_loader
def load_user(id):
    return ADMIN_USERS[int(id)]


#---------------------------------------------------------------------
@app.before_first_request
def before_first_request():
    with app.app_context():
        current_app.yml_products = []
        current_app.yml_tags = []
        #初始化g.db
        db = connect_db()
        for product in query_db1(db, 'select * from product'):
            current_app.yml_products.append(Product(product))
        for tag in query_db1(db, 'select * from tag order by count desc limit 12'):
            current_app.yml_tags.append(Tag(tag))
            #关闭g.db
        db.close()

#
@app.before_request
def before_request():
    g.db = connect_db()


#
@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()


#
@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404


# register view actions------------------------------------------------------
#view actions
@app.route('/')
def index():
    today_products = biz.getTodayProducts()
    today_products_rows = []
    for i in range(0, 9, 3):
        today_products_rows.append(today_products[i:i + 3])
    return render_template('index.html',
                           title=u'云目录 | yunmulu.net'
        , pagetitle=u'欢迎来到"云目录"！'
        , todayproductsrows=today_products_rows
        , todaynews=biz.getTodayNews()
        , tags=current_app.yml_tags)


#产品详情页面
@app.route('/product/<name>')
def product(name):
    #mark
    if name:
        p = biz.getProductByName(name)
        if p:
            return render_template('product.html'
                , pagetitle=u''
                , product=p
                , tags=current_app.yml_tags)
    return abort(404)


#产品列表页面
@app.route('/products')
@app.route('/products/<cate>')
def products(cate=None):
    if cate:#指定分类
        ps = []
        # TODO
        if cate.lower() == 'iaas':
            ps = biz.queryProductsByCate(cate)
        elif cate.lower() == 'paas':
            ps = biz.queryProductsByCate(cate)
        elif cate.lower() == 'saas':
            ps = biz.queryProductsByCate(cate)
        elif cate.lower() == 'openapi':
            ps = biz.queryProductsByCate(cate)
        else:
            abort(404)
    else:
        #随机产品
        ps = random.sample(app.yml_products, 10)
    return render_template('products.html'
        , pagetitle=u'云产品浏览'
        , products=ps
        , tags=current_app.yml_tags)


#标签页面
@app.route('/tag/<tag>')
def tag(tag):
    if tag:
        ps = biz.queryProductsByTag(tag)
        return render_template('products.html'
            , pagetitle=u'云产品标签浏览'
            , products=ps
            , tags=current_app.yml_tags)


#搜索方法
@app.route('/query')
def query():
    kw = request.values.get('kw', '')
    if kw:
        ps = biz.queryProducts(kw)
        return render_template('query.html'
            , haskw=True
            , products=ps
            , keyword=kw
            , pagetitle=u'产品查询结果'
            , tags=current_app.yml_tags)
    else:
        return render_template("query.html"
            , haskw=False
            , products=[]
            , pagetitle=u"产品查询结果"
            , tags=current_app.yml_tags)


#知识页面
@app.route('/kl')
def knowledge():
    return render_template('knowledge.html', pagetitle=u'云计算知识'
        , tags=current_app.yml_tags)

#
@app.route('/about')
def about():
    return render_template('about.html', pagetitle=u'关于'
        , tags=current_app.yml_tags)


#以下admin页面==================================================================

@app.route('/admin/login', methods=('GET', 'POST'))
def admin_login():
    if request.method == "POST" and "username" in request.form:
        username = request.form["username"]
        password = request.form["password"]
        if username in ADMIN_USERS_DICT:
            user = ADMIN_USERS_DICT[username]
            #匹配密码
            if password == user.password:
                remember = request.form.get("remember", "no") == "yes"
                if login_user(ADMIN_USERS_DICT[username], remember=remember):
                    return redirect(request.args.get("next") or url_for("admin"))
            #密码错误
            else:
                return render_template("admin/login.html", msg=u'用户名/密码错误')
        else:
            return render_template("admin/login.html", msg=u'用户名/密码错误')
    return render_template("admin/login.html")


@app.route("/admin/logout")
@login_required
def admin_logout():
    logout_user()
    #flash("Logged out.")
    return redirect(url_for("index"))


@app.route('/admin')
@login_required
def admin():
    return render_template('admin/admin.html')


@app.route('/admin/query')
@login_required
def admin_query():
    kw = request.values.get('name', '')
    ps = biz.queryProducts(kw)
    return render_template('admin/products.html', products=ps)


@app.route('/admin/product', methods=('GET', 'POST'))
@login_required
def admin_product():
    #如果有fid参数则为新增 如果有pid参数则为更新
    id = request.values.get('id', '')
    if request.method == 'GET':
        if id != '':
            #
            p = biz.getFreshProduct(id)
            #判断product
            if p is None:
                return abort(404)
            else:
                return render_template('admin/product.html', product=p)
        else:
            return abort(404)
    elif request.method == 'POST':
        #更新或保存
        name = request.values.get('name', '')
        eName = request.values.get('eName', '')
        categoryTags = request.values.get('categoryTags', '')
        featureTags = request.values.get('featureTags', '')
        logoUrl = request.values.get('logoUrl', '')
        pageUrl = request.values.get('pageUrl', '')
        caption = request.values.get('caption', '')
    else:
        abort(404)


#测试用
@app.route('/appinfo',methods=['POST','GET'])
def appinfo():
    data = request.data
    return render_template('appinfo.html'
        , app=app.__str__()
        , req=request
        , g=g
        , a=app)



# main
if __name__ == '__main__':
    app.run()












